package com.cly.utils;

import com.cly.result.exception.ServiceException;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.concurrent.CompletableFuture;
import java.util.function.Supplier;

/**
 * 异步工具类
 *
 * @author by 春风能解释
 * <p>
 * 2024/8/5
 */
@Component
@Slf4j
public class AsyncUtils {

    /**
     * 线程池
     */
    @Resource(name = "customThreadPoolTaskExecutor")
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    /**
     * 异步编排方法
     *
     * @param fun 方法体
     * @param <T> 类型
     * @return 异步返回值
     */
    public <T> T get(Supplier<T> fun) {
        return CompletableFuture.supplyAsync(() -> {
                    try {
                        return fun.get();
                    } catch (Exception e) {
                        throw new ServiceException(e);
                    }
                }, threadPoolTaskExecutor)
                .join();
    }

    /**
     * 异步编排方法
     *
     * @param fun 方法体
     */
    public void get(Runnable fun) {
        CompletableFuture.runAsync(fun, threadPoolTaskExecutor)
                .join();
    }

}
